package com.ilxqx.framework.system.controller.hook.inner;

import com.google.common.collect.Lists;
import com.ilxqx.framework.system.controller.hook.PreModify;
import com.ilxqx.framework.system.entity.anno.FileKey;
import com.ilxqx.framework.system.upload.qiniu.service.QiNiuImgUploadService;
import com.ilxqx.framework.system.util.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 检查文件标识改变，用于删除旧文件
 * @author venus
 */
@Component
@Slf4j
@Order(1)
public class ChangedFileKeyChecker implements PreModify {

	private final QiNiuImgUploadService qiNiuImgUploadService;

	@Autowired
	public ChangedFileKeyChecker(QiNiuImgUploadService qiNiuImgUploadService) {
		this.qiNiuImgUploadService = qiNiuImgUploadService;
	}

	/**
	 * 预处理
	 *
	 * @param entity 实体对象
	 * @param form   表单对象
	 * @param processingData 处理产生的数据
	 */
	@Override
	public void handle(Object entity, Object form, Map<String, Object> processingData) {
		List<String> keys = Lists.newArrayList();
		List<Field> fileKeyFields = ReflectionUtils.getAnnotatedFields(entity.getClass(), FileKey.class);
		fileKeyFields.forEach(field -> {
			if (!CharSequence.class.isAssignableFrom(field.getType())) {
				// 非字符串类型，跳过
				return;
			}
			Field formField = org.springframework.util.ReflectionUtils.findField(form.getClass(), field.getName());
			if (formField == null) {
				// 找不到，直接跳过
				return;
			}
			Object fieldValue = ReflectionUtils.getFieldValue(field, entity);
			Object formFieldValue = ReflectionUtils.getFieldValue(formField, form);
			if (fieldValue == null) {
				if (formFieldValue != null) {
					keys.add(formFieldValue.toString());
				}
				// 跳过
				return;
			}
			if (formFieldValue == null) {
				// 需要删除原有的文件key
				this.qiNiuImgUploadService.delete(fieldValue.toString());
				return;
			}
			if (!StringUtils.equals(fieldValue.toString(), formFieldValue.toString())) {
				// 不相等，说明文件改变了，需要删除旧文件
				this.qiNiuImgUploadService.delete(fieldValue.toString());
				// 同时添加新的文件标识符
				keys.add(formFieldValue.toString());
			}
		});
		processingData.put("keys", keys);
	}

}
